# /home/code/script/monitor/DingTalk.py
import requests
import time
import urllib
import hmac
import hashlib
import base64
import json
from envparse import env
import os
import logging

# 配置日志
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(levelname)s - %(message)s',
    handlers=[
        # logging.FileHandler('/home/code/script/monitor/dingtalk.log'),
        logging.StreamHandler()
    ]
)

logger = logging.getLogger(__name__)

env.read_envfile()

WEBHOOK = os.environ.get('WEBHOOK')
SECRET = os.environ.get('SECRET')

class DingTalkPushUtil:
    
    def __init__(self):
        self.headers = {'Content-Type': 'application/json'}
        logger.info("DingTalkPushUtil initialized")

    def getDingUrl(self):
        try:
            timestamp = round(time.time()*1000)
            secret_enc = SECRET.encode("utf-8")
            string_to_sign = '{}\n{}'.format(timestamp, SECRET)
            string_to_sign_enc = string_to_sign.encode('utf-8')
            hmac_code = hmac.new(secret_enc, string_to_sign_enc, digestmod=hashlib.sha256).digest()
            sign = urllib.parse.quote_plus(base64.b64encode(hmac_code))
            dingUrl = "{}&timestamp={}&sign={}".format(WEBHOOK, timestamp, sign)
            logger.debug("Generated DingTalk URL successfully")
            return dingUrl
        except Exception as e:
            logger.error(f"Failed to generate DingTalk URL: {e}")
            raise

    def send_text(self, content: str):
        """
        发送文本
        @param content: str, 文本内容
        """
        try:
            data = {"msgtype": "text", "text": {"content": content}}
            url = self.getDingUrl()
            logger.info(f"Sending text message: {content}")
            
            response = requests.post(
                url=url,
                data=json.dumps(data),
                headers=self.headers,
                timeout=10
            )
            
            logger.info(f"Text message sent. Status code: {response.status_code}")
            if response.status_code != 200:
                logger.warning(f"Unexpected status code: {response.text}")
                
            return response
        except Exception as e:
            logger.error(f"Failed to send text message: {e}")
            raise

    def send_md(self, title: str, content: str):
        """
        发送Markdown文本
        @param title: str, 标题
        @param content: str, 文本内容
        """
        try:
            data = {"msgtype": "markdown", "markdown": {"title": title, "text": content}}
            url = self.getDingUrl()
            logger.info(f"Sending markdown message. Title: {title}")
            
            response = requests.post(
                url=url,
                data=json.dumps(data),
                headers=self.headers,
                timeout=10
            )
            
            logger.info(f"Markdown message sent. Status code: {response.status_code}")
            if response.status_code != 200:
                logger.warning(f"Unexpected status code: {response.text}")
                
            return response
        except Exception as e:
            logger.error(f"Failed to send markdown message: {e}")
            raise

if __name__ == "__main__":
    # 示例用法
    try:
        dingtalk = DingTalkPushUtil()
        dingtalk.send_text("测试消息")
        # dingtalk.send_md("测试标题", "## 测试内容\n\n- 列表项1\n- 列表项2")
        logger.info("Script executed successfully")
    except Exception as e:
        logger.error(f"Script execution failed: {e}")